<template>
  <div class="app-container">
    <el-row>
      <el-card>
        <el-row class="text-right m-b">
          <el-input v-model="search" placeholder="输入关键字搜索" style="width: 400px;" />
          <el-button icon="el-icon-plus" type="primary" @click="handleAdd()">添加检查人员</el-button>
          <el-table
            :data="tableData.filter(data => !search || data.checkName.toLowerCase().includes(search.toLowerCase()) ||
              data.checkWeek.toLowerCase().includes(search.toLowerCase()) ||
              data.checkTime.toLowerCase().includes(search.toLowerCase()) ||
              data.checkPhone.toLowerCase().includes(search.toLowerCase()))"
            style="width: 100%"
            stripe="true"
            maxheight="100"
          >
            <!-- label是显示的标签，prob是对应data当中的名称，每一个对象当中都应该包含prop -->
            <el-table-column label="序号" align="center" type="index" :index="indexMethod" width="50%" prop="id" />
            <!-- 姓名 -->
            <el-table-column label="检查人员" prop="checkName" align="center">
              <template slot-scope="{row}">
                <span>{{ row.checkName }}</span>
              </template>
            </el-table-column>
            <!-- 星期 -->
            <el-table-column label="星期" prop="checkWeek" align="center">
              <template slot-scope="{row}">
                <span>{{ row.checkWeek }}</span>
              </template>
            </el-table-column>
            <!-- 时段 -->
            <el-table-column label="时段" prop="checkTime" align="center">
              <template slot-scope="{row}">
                <span>{{ row.checkTime }}</span>
              </template>
            </el-table-column>
            <!-- 电话 -->
            <el-table-column label="联系方式" prop="checkPhone" align="center">
              <template slot-scope="{row}">
                <span>{{ row.checkPhone }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-card>
    </el-row>
    <!-- 编辑管理员的弹窗显示 -->
    <el-dialog :visible.sync="dialogEditFormVisible" width="25%">
      <el-form ref="tempTableData" :model="tempTableData" :rules="rules" label-position="center" label-width="90px">
        <el-form-item label="姓名" prop="checkName">
          <el-select v-model="tempTableData.checkName" filterable placeholder="请选择">
            <el-option v-for="item in optionsManage" :key="item.adminName" :label="item.adminName" :value="item.adminName" />
          </el-select>
        </el-form-item>
        <el-form-item label="星期" prop="checkWeek">
          <el-select v-model="tempTableData.checkWeek" filterable placeholder="请选择">
            <el-option v-for="item in optionsWeek" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="时段" prop="checkTime">
          <el-select v-model="tempTableData.checkTime" filterable placeholder="请选择">
            <el-option v-for="item in optionsTime" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="checkPhone">
          <el-input :disabled="true" v-model="tempTableData.checkPhone" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAction()">取消</el-button>
        <el-button type="primary" @click="editData()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 新增管理员的弹窗显示 -->
    <el-dialog :visible.sync="dialogAddFormVisible" width="25%">
      <el-form ref="tempTableData" :model="tempTableData" :rules="rules" label-position="center" label-width="90px">
        <el-form-item label="姓名" prop="checkName">
          <el-select v-model="tempTableData.checkName" filterable placeholder="请选择">
            <el-option v-for="item in optionsManage" :key="item.adminName" :label="item.adminName" :value="item.adminName" />
          </el-select>
        </el-form-item>
        <el-form-item label="星期" prop="checkWeek">
          <el-select v-model="tempTableData.checkWeek" filterable placeholder="请选择">
            <el-option v-for="item in optionsWeek" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="时段" prop="checkTime">
          <el-select v-model="tempTableData.checkTime" filterable placeholder="请选择">
            <el-option v-for="item in optionsTime" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAction()">取消</el-button>
        <el-button type="primary" @click="addData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addCheck, editCheck, getCheck, deleteCheck } from '@/api/checkTable'
import { getManager } from '@/api/accountManage'
export default {
  data() {
    return {
      tableData: [],
      optionsWeek: [{
        value: '周一',
        label: '周一'
      }, {
        value: '周二',
        label: '周二'
      }, {
        value: '周三',
        label: '周三'
      }, {
        value: '周四',
        label: '周四'
      }, {
        value: '周五',
        label: '周五'
      }],
      optionsTime: [{
        value: '中午',
        label: '中午'
      }, {
        value: '下午',
        label: '下午'
      }, {
        value: '晚上',
        label: '晚上'
      }],
      optionsManage: [],
      tempTableData: [{
        checkId: '',
        checkName: '',
        checkWeek: '',
        checkTime: '',
        checkPhone: ''
      }],
      search: '',
      dialogEditFormVisible: false,
      dialogAddFormVisible: false,
      rules: {
        checkName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        checkWeek: [{ required: true, message: '请选择星期', trigger: 'blur' }],
        checkTime: [{ required: true, message: '请选择时段', trigger: 'blur' }],
        checkPhone: [{ required: true, message: '填写手机号码', trigger: 'blur' }, { validator: this.checkPHONE, trigger: 'blur' }]
      }
    }
  },
  created() {
    getCheck().then((result) => {
      this.tableData = result.data.tCheckList
      // console.log(result.data)
    }).catch(() => {
      console.log('获取信息失败，请检查！')
    }
    )
    getManager().then((result) => {
      this.optionsManage = result.data.adminList
      // console.log(result.data)
    }).catch(() => {
      console.log('获取信息失败，请检查！')
    }
    )
  },
  methods: {
    checkPHONE(rule, value, callback) {
      const mobileReg = /^1[3456789]\d{9}$/
      if (!mobileReg.test(value)) {
        callback(new Error('手机号格式不正确！'))
      } else {
        callback()
      }
    },
    handleEdit(row) {
      this.tempTableData = Object.assign({}, row)
      this.tempTableData.checkId = row.checkId
      this.tempTableData.checkName = row.checkName
      this.tempTableData.checkWeek = row.checkWeek
      this.tempTableData.checkTime = row.checkTime
      // const optionsManage_index = this.optionsManage.findIndex(item => item.adminName === this.tempTableData.checkName)
      this.tempTableData.checkPhone = row.checkPhone
      console.log(row.checkName)
      this.dialogEditFormVisible = true
    },
    // 现在想要实现的效果是，更新完数据之后，数据要能够直接显示在原表单里。
    editData() {
      this.$refs['tempTableData'].validate((valid) => {
        if (valid) {
          // 找到对应数据的行
          const index = this.tableData.findIndex(item => item.checkId === this.tempTableData.checkId)
          if (index !== -1) {
            editCheck({
              'checkId': this.tempTableData.checkId,
              'checkName': this.tempTableData.checkName,
              'checkWeek': this.tempTableData.checkWeek,
              'checkTime': this.tempTableData.checkTime,
              'checkPhone': this.tempTableData.checkPhone
            }).then(() => {
              // 找到对应的行，更新数据
              console.log(this.tempTableData.checkPhone)
              this.tableData.splice(index, 1, this.tempTableData)
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              this.dialogEditFormVisible = false
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '编辑失败，请检查!'
              })
            }
            )
          }
        } else {
          this.$message({
            showClose: true,
            message: '请再次核对信息！',
            type: 'error'
          })
        }
      })
    },
    cancleAction() {
      this.dialogAddFormVisible = false
      this.dialogEditFormVisible = false
      this.tempTableData = [{
        checkId: '',
        checkName: '',
        checkWeek: '',
        checkTime: '',
        checkPhone: ''
      }]
    },
    handleDelete(index, row) {
      this.$confirm('此操作将删除该管理员的检查信息，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning' }).then(() => { // 找到要删除的员工在数组中的索引
        const index = this.tableData.indexOf(row) // 从数组中删除员工
        deleteCheck(this.tableData[index].checkId).then(() => {
          this.tableData.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '删除失败，请检查!'
          })
        }
        )
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      }
      )
      console.log(index, row)
    },
    // 设置ID号
    indexMethod(index) {
      return index + 1
    },
    handleAdd() {
      this.cancleAction()
      this.dialogAddFormVisible = true
    },
    addData() {
      this.$refs['tempTableData'].validate((valid) => {
        if (valid) {
          this.$confirm('确认要添加？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning' }).then(() => {
            const optionsManage_index = this.optionsManage.findIndex(item => item.adminName === this.tempTableData.checkName)
            this.tempTableData.checkPhone = this.optionsManage[optionsManage_index].adminPhone
            addCheck({
              'checkName': this.tempTableData.checkName,
              'checkWeek': this.tempTableData.checkWeek,
              'checkTime': this.tempTableData.checkTime,
              'checkPhone': this.tempTableData.checkPhone
            }).then(() => {
              this.tableData.push(this.tempTableData)
              this.dialogAddFormVisible = false
              this.$message({
                type: 'success',
                message: '增加成功!'
              })
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '增加失败，请检查!'
              })
            }
            )
          })
        } else {
          this.$message({
            showClose: true,
            message: '请检查信息是否填写完整！',
            type: 'error'
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.el-form {
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
}
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-input {
  position:relative;
  font-size:14px;
  display:inline-block;
  width: 223.1px;
}
</style>
